#from sls_uavPPDialog import Ui_UAVPPDialog
from sls_ugvPPDialog import Ui_UGVPPDialog
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                            QHBoxLayout, QPushButton, QLineEdit, QListWidget, 
                            QLabel, QMessageBox,QDialog, QMenu)
from pyproj import Geod
from datetime import datetime
from sls_mirrors import sls_agent
from PyQt6.QtCore import Qt
import path_planner1
import json
import os
import polyline
from sls_ugvNormalMissions.full_coverage_omega_steering import FullCoverageOmegaSteering
from sls_ugvNormalMissions.abline_arc_turning import TrajectoryGenerator
# fc = FullCoverageOmegaSteering()
# print(fc.get_path_points_lon_lat())
mission_table={"MissionsStanelyController",
               "MissionsNonlinearSteerController",
               "MissionsMPCSteerController",
               "MissionsSTM32Serialpub",
               "MissionsEventTriggeredASTLFController"}
uav_ugv_table={"ugv1","ugv2",}
planners_table = {"全覆盖": 0,
                # "Planner2": 1,
                }

class UGVPPDialog(QDialog):
    def __init__(self, parent, menu:QMenu):
        super().__init__(parent)
        self.id = id
        self.parent = parent
        self.menu = menu
        self.parent.ui.uavPathPlan.setEnabled(False)
        self.parent.ui.ugvPathPlan.setEnabled(False)
        self.parent.ui.tools.setEnabled(False)
        # 初始化UI
        self.ui = Ui_UGVPPDialog()
        self.ui.setupUi(self)
        self.setWindowTitle(f"无人车的路径规划")
        
        self.click_points = []
        self.path_points = []
        self.marker_name = []
        self.takeoffDict = {}
        self.init_mission_ui()
        self.init_history_plan_ui()
        self.parent.notifyClass.add_notify_Cordinate(self.on_click_point)
        self.ui.pushButton_remove.clicked.connect(self.remove_point)
        self.ui.pushButton_pathplan.clicked.connect(self.show_path)
        self.ui.tabWidget.currentChanged.connect(self.on_tab_changed)  
        self.current_method = "abline" 
        self.ui.comboBox_planners.currentTextChanged.connect(self.switch_page)
        self.ui.pushButton_publish.clicked.connect(self.on_publish)  
        self.ui.pushButton_replan.clicked.connect(self.clearallset)
        self.ui.pushButton_save_path.clicked.connect(self.save_plan_tojson)
        self.ui.pushButton_del_history_path.clicked.connect(self.del_history_plan)
        self.ui.checkBox_isUse_historyPlan.stateChanged.connect(self.use_history_path)
        self.ui.comboBox_history_paths.currentTextChanged.connect(self.show_history_path)
        self.ui.pushButton_use_history_boundary.clicked.connect(self.use_history_boundary)
        self.ui.pushButton_save_path_2.clicked.connect(self.save_clickpath_tojson)


        self.every_interpolate_point = []
        self.path_points_lon_lat = []
        self.path_points_lat_lon_tuple = []
        
        self.clearallset()
        
    def switch_page(self):
        # 根据当前文本切换页面
        current_text = self.ui.comboBox_planners.currentText()
        if current_text in planners_table:
            target_index = planners_table[current_text]
            self.ui.stackedWidget.setCurrentIndex(target_index)
            self.clearallset()

    def set_height(self):
        if self.ui.checkBox_isSet_height.checkState() == Qt.CheckState.Unchecked:
            self.ui.doubleSpinBox_mission_height.setDisabled(True)
        elif self.ui.checkBox_isSet_height.checkState() == Qt.CheckState.Checked:
            self.ui.doubleSpinBox_mission_height.setDisabled(False)

    def on_tab_changed(self, index):
        if index == 0:
            self.current_method = "abline"
        elif index == 1:
            self.current_method = "planner"
        self.clearallset()

    def init_mission_ui(self):
        self.ui.comboBox_mission.clear()
        self.ui.comboBox_mission.addItems(sorted(mission_table))
        self.ui.comboBox_uav_ugv.clear()
        self.ui.comboBox_uav_ugv.addItems(sorted(uav_ugv_table))
        self.ui.comboBox_planners.clear()
        self.ui.comboBox_planners.addItems(sorted(planners_table.keys()))

    def init_history_plan_ui(self):
        try:
            with open("pathsfile.json", "r", encoding="utf-8") as file:
                data = json.load(file)
            all_plan_names = [plan_data["plan_name"] for plan_data in data]
        except FileNotFoundError:
            return None
        except json.JSONDecodeError:
            return None
        self.ui.comboBox_history_paths.clear()
        self.ui.comboBox_history_paths.addItems(all_plan_names)
        self.ui.comboBox_history_boundaries.clear()
        self.ui.comboBox_history_boundaries.addItems(all_plan_names)
        
    def use_history_boundary(self):
        self.clearallset()
        plan_name = self.ui.comboBox_history_boundaries.currentText()
        plan_data = self.read_plan_fromjson(plan_name)
        if  plan_data == None:
            self.ui.label_planner_info.setText("该历史任务没有边界数据，请重新选择")
            self.ui.label_planner_info.setStyleSheet("QLabel { color: red; }")
            return
        self.click_points = []
        self.click_points = plan_data["boundary_points"]
        color = "#3010A3"
        boundary_points = [[point[1], point[0]] for point in self.click_points]
        boundary_points.append(boundary_points[0])
        self.parent.del_polyline("boundary" )
        self.parent.add_polyline(boundary_points,color,"boundary" )
        self.ui.label_planner_info.setText("已加载历史任务区域，可以进行路径规划")
        self.ui.label_planner_info.setStyleSheet("QLabel { color: black; }")


    def use_history_path(self):
        self.clearallset()
        if self.ui.checkBox_isUse_historyPlan.checkState() == Qt.CheckState.Unchecked:
            self.parent.del_polyline("history_path" )
            self.parent.del_polyline("history_boundary" )
            self.ui.label_history_path_info.clear()
            return 
        elif self.ui.checkBox_isUse_historyPlan.checkState() == Qt.CheckState.Checked:
            self.ui.label_history_path_info.setText("使用历史路径规划任务")
            self.show_history_path()
            
    
    def remove_point(self):
        if self.click_points: 
            self.click_points.pop()
            if self.marker_name:
                name = self.marker_name.pop()
                self.parent.del_marker(name)
            if self.click_points:
                if self.current_method == "planner":
                    color = "#3010A3"
                    boundary_points = [[point[1], point[0]] for point in self.click_points]
                    boundary_points.append(boundary_points[0])
                    self.parent.del_polyline("boundary" )
                    self.parent.add_polyline(boundary_points,color,"boundary" )
                if self.current_method == "abline":
                    path_points = [[point[1], point[0]] for point in self.click_points]
                    color = "#E20D29"
                    self.parent.del_polyline("planed_path")
                    self.parent.add_polyline(path_points,color,"planed_path")
                    self.parent.del_polyline("planed_path")

    
    def on_click_point(self,latitude,longitude):
        self.click_points.append([latitude,longitude])
        if self.current_method == "abline":
            self.marker_name.append(f"path_point*{len(self.click_points)}" )
            self.parent.add_marker(latitude, longitude,f"path_point*{len(self.click_points)}")
            path_points = [[point[1], point[0]] for point in self.click_points]
            self.path_points = [[point[1], point[0]] for point in self.click_points]
            color = "#0DE21F"
            self.parent.del_polyline("planed_path")
            self.parent.add_polyline(path_points,color,"planed_path")
            self.ui.label_ok_erro.clear()

        if self.current_method == "planner":
            self.marker_name.append(f"boundary_point*{len(self.click_points)}")
            self.parent.add_marker(latitude, longitude, f"boundary_point*{len(self.click_points)}")
            color = "#3010A3"
            boundary_points = [[point[1], point[0]] for point in self.click_points]
            boundary_points.append(boundary_points[0])
            self.parent.del_polyline("boundary" )
            self.parent.add_polyline(boundary_points, color, "boundary" )
            self.parent.del_polyline("planed_path")
            # self.ui.pushButton_pathplan.setEnabled(len(self.click_points) >= 3)

    def show_path(self):
        current_text = self.ui.comboBox_planners.currentText()
        print(current_text)
        if planners_table[current_text] == 0:
            boundary_points = [[point[1], point[0]] for point in self.click_points]
            print(boundary_points)
            min_turning_radius = self.ui.doubleSpinBox_min_turning_radius.value()
            tractor_length = self.ui.doubleSpinBox_tractor_length.value()
            tractor_width = self.ui.doubleSpinBox_tractor_width.value()
            wheel_length = self.ui.doubleSpinBox_wheel_length.value()
            wheel_width = self.ui.doubleSpinBox_wheel_width.value()
            interval = self.ui.doubleSpinBox_interval.value()
            # print("=== FullCoverageOmegaSteering 参数检查 ===")
            # print(f"boundary_points: {boundary_points}")
            # print(f"boundary_points 长度: {len(boundary_points)}")
            # print(f"start_point: {boundary_points[0]}")
            # print(f"terminal_point: {boundary_points[-1]}")
            # print(f"interval: {interval}")
            # print(f"min_turning_radius: {min_turning_radius}")
            # print(f"tractor_length: {tractor_length}")
            # print(f"tractor_width: {tractor_width}")
            # print(f"wheel_width: {wheel_width}")
            # print(f"wheel_length: {wheel_length}")

            try:
                fc = FullCoverageOmegaSteering(field_boundary_coords=boundary_points,
                                            start_point=boundary_points[0],
                                            terminal_point=boundary_points[-1],
                                            forward_interval=interval,
                                            distance=10,
                                            MIN_TURNING_RADIUS=min_turning_radius,
                                            TRACTOR_LENGTH=tractor_length,
                                            TRACTOR_WIDTH=tractor_width,
                                            WHEEL_WIDTH=wheel_width,
                                            WHEEL_LEN=wheel_length)
                self.path_points_lon_lat = fc.get_path_points_lon_lat()
                self.path_points_lat_lon = fc.get_path_points_lat_lon()
                self.path_points_lat_lon_tuple = [(float(lat_lon[0]), float(lat_lon[1])) for lat_lon in self.path_points_lat_lon]
                self.path_points = self.path_points_lat_lon
                self.path_points_lon_lat = [[float(lon_lat[0]), float(lon_lat[1])] for lon_lat in self.path_points_lon_lat]
            except Exception as e:
                self.click_points = []
                self.clearallset()
                self.ui.label_planner_info.clear()
                self.ui.label_planner_info.setText("路径未生成，请重新选择任务区域")
                self.ui.label_planner_info.setStyleSheet("QLabel { color: red; }")
                print(f"规划算法出错: {e}")
                return
            # print(self.path_points_lon_lat)
            # self.path_points = path_planner1.generate_coverage_path(params, boundary_points) 

        elif planners_table[current_text] == 1:
            pass
        self.ui.label_ok_erro.clear()
        self.ui.label_planner_info.setText("路径规划成功,如需保存路径请输入路径名：")
        self.ui.label_planner_info.setStyleSheet("QLabel { color: black; }")
        color = "#0DE2B4"
        self.parent.del_polyline("planed_path")
        self.parent.add_polyline(self.path_points_lon_lat,color,"planed_path")
        print(self.path_points_lon_lat)
        self.parent.del_sortedMarkers("boundary_point")
        self.marker_name = []

    def show_history_path(self):
        plan_name = self.ui.comboBox_history_paths.currentText()
        plan_data = self.read_plan_fromjson(plan_name)
        if not plan_data:
            return

        # 清理旧的显示
        self.parent.del_polyline("history_path")
        self.parent.del_polyline("history_boundary")

        # ======== 自动规划任务（完整 boundary + path_points） ========
        if "path_points" in plan_data and "boundary_points" in plan_data:
            # 规划路径
            self.path_points = plan_data["path_points"]

            # 边界：lat/lon → lon/lat
            boundary_points = [[p[1], p[0]] for p in plan_data["boundary_points"]]

            # 绘制历史路径
            self.parent.add_polyline(self.path_points, "#E20D29", "history_path")

            # 绘制历史边界
            self.parent.add_polyline(boundary_points + [boundary_points[0]],
                                    "#3010A3", "history_boundary")

        # ======== 打点路径任务 clickpath（只有 points） ========
        elif plan_data.get("type") == "clickpath":
            self.path_points = [[p[1], p[0]] for p in plan_data["points"]]  # lat/lon → lon/lat

            # 绘制历史路径（无边界）
            self.parent.add_polyline(self.path_points, "#E20D29", "history_path")

        else:
            # 无法识别的数据类型
            self.ui.label_history_path_info.setText("历史路径格式错误")
            return

        

    def on_publish(self):
        if len(self.path_points)<1:
            self.ui.label_ok_erro.setText("当前任务不包含任何路径，请重新规划")
            self.ui.label_ok_erro.setStyleSheet("QLabel { color: red; }")
            return

        agent:sls_agent.MirrorsAgent = self.parent.mirror_agent
        mission_current_text = self.ui.comboBox_mission.currentText()
        uav_ugv_current_text = self.ui.comboBox_uav_ugv.currentText()
        plan_name = self.ui.comboBox_history_paths.currentText()
        plan_data = self.read_plan_fromjson(plan_name)
        if self.ui.checkBox_isUse_historyPlan.checkState() == Qt.CheckState.Unchecked:
            if self.current_method == "abline":
                abline_turning_radius=self.ui.doubleSpinBox_turing_radius.value()
                abline_interval = self.ui.doubleSpinBox_interval.value()
                interpolator = TrajectoryGenerator()
                click_point_tuple = [tuple(i) for i in self.click_points]
                path_tuple_lat_lon = interpolator.generate_fillet_path(click_point_tuple,abline_interval,abline_turning_radius)
                # self.parent.add_polyline_tuple_lat_lon(path_tuple_lat_lon,"#10A352","path")
        # # 显示路径标志，仅用于调试
        # self.parent.del_allmarkers()
        # for i in path_tuple_lat_lon:
        #     lat,lon = i
        #     print(lat,lon)
        #     self.parent.add_marker(lat, lon,f"path_point*{i}")
        # if self.current_method == "abline":
        #     pass
        #     every_path_tuple_lat_lon = polyline.encode(path_tuple_lat_lon,precision=8)
        #     self.multitudePoints = {
        #         "missionsType": mission_current_text,
        #         "datasets":{
        #             "lat_lon_encoded":every_path_tuple_lat_lon
        #         }
        #     }
        #     self.SaveTxtFile("clicked_points/UGV_Points", "UgvTrackPoint", path_tuple_lat_lon)
        # elif self.current_method == "planner" or self.ui.checkBox_isUse_historyPlan.checkState() == Qt.CheckState.Checked:
        #         every_interpolate_point_encoded = polyline.encode(self.path_points_lat_lon_tuple,precision=8)
        #         print(every_interpolate_point_encoded)
        #         self.multitudePoints = {
        #         "missionsType": mission_current_text,
        #         "datasets":{
        #             "lat_lon_encoded":every_interpolate_point_encoded
        #         }
        #     }
        #         self.SaveTxtFile("clicked_points/UGV_Points", "full_coverage_omega_steering", self.path_points_lat_lon_tuple)
        if self.ui.checkBox_isUse_historyPlan.checkState() == Qt.CheckState.Checked:
            # 历史路径直接用 self.path_points（lon,lat）
            points = [(p[1], p[0]) for p in self.path_points]  # 转成 (lat,lon)
            every_encoded = polyline.encode(points, precision=8)

            self.multitudePoints = {
                "missionsType": mission_current_text,
                "datasets": {
                    "lat_lon_encoded": every_encoded
                }
            }
            self.SaveTxtFile("clicked_points/UGV_Points", "UgvTrackPoint", path_tuple_lat_lon)
        else:
            # === 原有 planner / abline ===
            if self.current_method == "abline":
                every_path_tuple_lat_lon = polyline.encode(path_tuple_lat_lon,precision=8)
                self.multitudePoints = {
                    "missionsType": mission_current_text,
                    "datasets":{
                        "lat_lon_encoded":every_path_tuple_lat_lon
                    }
                }

            elif self.current_method == "planner":
                every_interpolate_point_encoded = polyline.encode(self.path_points_lat_lon_tuple,precision=8)
                self.multitudePoints = {
                    "missionsType": mission_current_text,
                    "datasets":{
                        "lat_lon_encoded":every_interpolate_point_encoded
                    }
                }
                self.SaveTxtFile("clicked_points/UGV_Points", "full_coverage_omega_steering", self.path_points_lat_lon_tuple)
        agent.append_mission_to_schedule(uav_ugv_current_text,self.multitudePoints)
        agent.request_scheduleUpdate_missions_list(uav_ugv_current_text)
        self.ui.label_ok_erro.setText("任务发布成功")
        self.clearallset()
        self.parent.del_polyline("history_path")
        self.parent.del_polyline("history_boundary")
        self.use_history_path()
        self.close()
            
    def SaveTxtFile(self, dir, filename, content):
        '''
        保存坐标数据到txt文件
        Args:
            dir      (str): 目标目录路径
            filename (str): 文件名（不含扩展名和时间戳）
            content (list): 坐标数据列表，格式为 [(lat1, lon1), (lat2, lon2), ...]
        '''
        if not content:
            self.parent.statusBar_signal.emit(filename + f" No Data to Save")
            return
        if not os.path.exists(dir):
            os.makedirs(dir)
        current_time = datetime.now()
        filename = filename + f"_{current_time.strftime('%Y-%m-%d_%H-%M-%S')}.txt"
        file_path = os.path.join(dir, filename)
        
        try:
            with open(file_path, 'w', encoding='utf-8') as file:
                for lat, lon in content:
                    file.write(f"{lat},{lon}\n")
            self.parent.statusBar_signal.emit(filename + f" Saving Success")
        except Exception as e:
            self.parent.statusBar_signal.emit(filename + f" Saving Failed")

    def save_plan_tojson(self):  
        plan_name = self.ui.lineEdit_path_name.text()
        if plan_name == "":
            self.ui.label_planner_info.setText("请输入路径名")
            self.ui.label_planner_info.setStyleSheet("QLabel { color: red; }")
            return
        if self.check_plan_name_exists(plan_name):
            self.ui.label_planner_info.setText(f"路径名称 '{plan_name}' 已存在，请重新命名")
            self.ui.label_planner_info.setStyleSheet("QLabel { color: red; }")
            return  
        if len(self.path_points)<1:
            self.ui.label_planner_info.setText("当前路径不包含任何路径点，请重新规划")
            self.ui.label_planner_info.setStyleSheet("QLabel { color: red; }")
            return
        plan_data = {
            "plan_name": plan_name,
            "boundary_points":self.click_points,
            "path_points": self.path_points,
        }
        if not os.path.exists("pathsfile.json"):
            with open("pathsfile.json", "w", encoding="utf-8") as file:
                json.dump([], file)
        with open("pathsfile.json", "r", encoding="utf-8") as file:
            data = json.load(file)
        data.append(plan_data)
        with open("pathsfile.json", "w", encoding="utf-8") as file:
            json.dump(data, file, indent=4, ensure_ascii=False)
        self.ui.label_planner_info.setText("路径保存成功，可在历史路径栏查看")
        self.ui.label_planner_info.setStyleSheet("QLabel { color: black; }")
        self.ui.lineEdit_path_name.clear()
        self.init_history_plan_ui()

    def save_clickpath_tojson(self):
        """保存打点任务路径（与规划任务共用 pathsfile.json）"""
        plan_name = self.ui.lineEdit_path_name_2.text().strip()
        if plan_name == "":
            self.ui.label_planner_info_2.setText("请输入打点任务名")
            self.ui.label_planner_info_2.setStyleSheet("QLabel { color: red; }")
            return

        if len(self.click_points) < 1:
            self.ui.label_planner_info_2.setText("当前任务不包含任何点，请先打点")
            self.ui.label_planner_info_2.setStyleSheet("QLabel { color: red; }")
            return

        # 若文件不存在则创建
        if not os.path.exists("pathsfile.json"):
            with open("pathsfile.json", "w", encoding="utf-8") as file:
                json.dump([], file)

        # 读取已有文件
        with open("pathsfile.json", "r", encoding="utf-8") as file:
            try:
                data = json.load(file)
            except json.JSONDecodeError:
                data = []

        # 检查重名（仅针对 clickpath 类型）
        for plan in data:
            if plan.get("plan_name") == plan_name and plan.get("type") == "clickpath":
                self.ui.label_planner_info_2.setText(f"任务名称 '{plan_name}' 已存在，请重新命名")
                self.ui.label_planner_info_2.setStyleSheet("QLabel { color: red; }")
                return

        # 保存数据
        plan_data = {
            "plan_name": plan_name,
            "type": "clickpath",           # 区分类型
            "points": self.click_points    # 保存用户打的点
        }
        data.append(plan_data)

        # 写回文件
        with open("pathsfile.json", "w", encoding="utf-8") as file:
            json.dump(data, file, indent=4, ensure_ascii=False)

        self.ui.label_planner_info_2.setText("打点任务保存成功，可在历史路径栏查看")
        self.ui.label_planner_info_2.setStyleSheet("QLabel { color: black; }")
        self.ui.lineEdit_path_name_2.clear()
        self.init_history_plan_ui()  # 复用已有下拉更新函数


    def read_plan_fromjson(self, plan_name):

        try:
            with open("pathsfile.json", "r", encoding="utf-8") as file:
                data = json.load(file)
            for plan_data in data:
                if plan_data["plan_name"] == plan_name:
                    return plan_data 
            return None
        except FileNotFoundError:
            return None
        except json.JSONDecodeError:
            return None
        
    def del_history_plan(self):
        plan_name = self.ui.comboBox_history_paths.currentText()
        try:
            with open("pathsfile.json", "r", encoding="utf-8") as file:
                data = json.load(file)
        
            initial_length = len(data) 
            data = [plan_data for plan_data in data if plan_data["plan_name"] != plan_name]
        
            if len(data) == initial_length:
                self.ui.label_history_path_info.setText(f"未找到路径名称为 '{plan_name}' 的数据")
                return False
        
            with open("pathsfile.json", "w", encoding="utf-8") as file:
                json.dump(data, file, indent=4, ensure_ascii=False)
            self.ui.label_history_path_info.setText(f"成功删除路径名称为 '{plan_name}' 的数据")
            if self.ui.comboBox_history_boundaries.currentText() == plan_name:
                self.parent.del_polyline("boundary" )
                self.click_points = []
            self.init_history_plan_ui()
            return True
        except FileNotFoundError:
            self.ui.label_history_path_info.setText("文件不存在")
            return False
        except json.JSONDecodeError:
            self.ui.label_history_path_info.setText("JSON 文件格式错误")
            return False
        
        
    def check_plan_name_exists(self, plan_name):
        try:
            with open("pathsfile.json", "r", encoding="utf-8") as file:
                data = json.load(file)
            for plan_data in data:
                if plan_data["plan_name"] == plan_name:
                    return True
            return False
        except FileNotFoundError:
            return False
        except json.JSONDecodeError:
            return False

    def clearallset(self):
        self.parent.del_polyline("planed_path")
        self.parent.del_polyline("boundary")
        self.parent.del_sortedMarkers("boundary_point")
        self.parent.del_sortedMarkers("path_point")
        self.ui.label_planner_info.setText("请在地图点击鼠标右键选择任务区域")
        self.ui.label_planner_info.setStyleSheet("QLabel { color: black; }")
        self.ui.label_ok_erro.clear()
        self.click_points = []
        self.path_points = []
        self.marker_name = []

    def keyPressEvent(self, event):
        # 检测是否按下 ESC 键
        if event.key() == Qt.Key.Key_Escape:
            self.clearallset()
            self.parent.del_polyline("history_path")
            self.parent.del_polyline("history_boundary")
            self.menu.setEnabled(True)
            self.parent.notifyClass.remove_notify_Cordinate(self.on_click_point)
        # 记得调用父类的方法以确保其他键盘事件正常处理
        super().keyPressEvent(event)

    def closeEvent(self, event):
        # 当对话框关闭时，重新启用父窗口的按钮
        self.clearallset()
        self.parent.del_polyline("history_path")
        self.parent.del_polyline("history_boundary")
        self.parent.ui.uavPathPlan.setEnabled(True)
        self.parent.ui.ugvPathPlan.setEnabled(True)
        self.parent.ui.tools.setEnabled(True)
        self.parent.notifyClass.remove_notify_Cordinate(self.on_click_point) 

    def interpolate_gps_points_pyproj(self, pointA, pointB, interval_meters):
        geod = Geod(ellps="WGS84")
        lon1, lat1 = pointA[1], pointA[0]
        lon2, lat2 = pointB[1], pointB[0]

        az12, az21, total_distance = geod.inv(lon1, lat1, lon2, lat2)

        points = [(lat1,lon1)]
        num_points = int(total_distance // interval_meters)

        for i in range(1, num_points):
            lon, lat, _ = geod.fwd(lon1, lat1, az12, i * interval_meters)
            points.append((lat, lon))

        points.append((lat2,lon2))
        return points